<?php
require_once("AbstractTag.php");

class TagParser {	
	public function parse($strSubject) {
		// TODO: > sa nu fie intre ghilimele
		$strSubject = preg_replace_callback("/<([a-zA-Z0-9_]+)\:([a-zA-Z0-9_]+)(.*?)>/",array($this,"parseStartTagCallback"),$strSubject);
		$strSubject = preg_replace_callback("/<\/([a-zA-Z0-9_]+)\:([a-zA-Z0-9_]+)>/",array($this,"parseEndTagCallback"),$strSubject);
		return $strSubject;
	}

	protected function parseStartTagCallback($tblMatches) {
		return $this->getTagInstance($tblMatches)->parseStartTag($this->getTagParameters($tblMatches[3]));
	}
	
	protected function parseEndTagCallback($tblMatches) {
		return $this->getTagInstance($tblMatches)->parseEndTag();
	}
	
	private function getTagInstance($tblMatches) {
		$strClassName = ucfirst($tblMatches[1]).ucfirst($tblMatches[2]).'Tag';
		if(!class_exists($strClassName)) throw new ViewException("Tag not found: ".$strClassName);
		return new $strClassName();
	}
	
	private function getTagParameters($strParameters) {
		// remove php tags from EL
		$strParameters = trim($strParameters);
		if(!$strParameters || $strParameters=="/") return array();
		preg_match_all('/([a-zA-Z0-9_]+)="(.*?)"/', $strParameters, $tblParameters, PREG_SET_ORDER);
		$tblOutput=array();
		foreach($tblParameters as $tblValues) {
			$tblOutput[trim($tblValues[1])]=trim($tblValues[2]);
		}
		return $tblOutput;
	}
}